﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;

namespace vulnanalyzer
{
    public partial class Form1 : Form, ICopyFilesDiag
    {
        public SettingsForWork setforwork = new SettingsForWork();

        public List<String> list = new List<String>();
        public int number = 0;
        public int numberI1 = 0;
        public int t = 0;
        public int len = 0;
        public bool Op = false;

        public System.ComponentModel.ISynchronizeInvoke SynchronizationObject { get; set; }
        
        //конструктор объекта
        public Form1()
        {
            InitializeComponent();

            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker2.WorkerReportsProgress = true;
            backgroundWorker2.WorkerSupportsCancellation = true;

            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            button4.Enabled = false;
            button2.Enabled = false;

            setforwork.howDownload.LoadFromDisk = false;
            setforwork.howDownload.LoadFile = new List<LoadFile>();
            setforwork.Service = new List<ItServices>();
            setforwork.Service.Clear();

            //заполнение поля стандартными типами программного обеспечения
            ItServices its1 = GetDefaultIts();
            its1.Name = "Рабочее место пользователя";
            setforwork.Service.Add(its1);
            ItServices its2 = GetDefaultIts();
            its2.Name = "Электронная почта";
            setforwork.Service.Add(its2);
            ItServices its3 = GetDefaultIts();
            its3.Name = "Доступ в Интернет";
            setforwork.Service.Add(its3);
            ItServices its4 = GetDefaultIts();
            its4.Name = "Файловое хранилище";
            setforwork.Service.Add(its4);

            //скрывается пятая вкладка - выдачи рисков(см. ТЗ 2 абзац)
            //При необходимости ее показать: tabPage5.Parent = tabControl1;
            tabPage5.Parent = null;
            tabPage4.Parent = null;
            tabPage3.Parent = null;
            tabPage2.Parent = null;
            
            
            
        }

        
        //Кнопка "Произвести скачивание" таб №1
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = false;
            button4.Enabled = true;
            radioButton1.Enabled = false;
            radioButton2.Enabled = false;

            if (setforwork.howDownload.LoadFromDisk)
            {
                List<String> TempFiles = new List<String>();
                String folderPath = folderBrowserDialog1.SelectedPath;
                String[] filesinpath = System.IO.Directory.GetFiles(folderPath,"*.xml");
                if (setforwork.howDownload.LoadFile.Count != 0)
                {
                    setforwork.howDownload.LoadFile.Clear();
                }
                foreach (String onefile in filesinpath)
                {
                    String test = onefile;
                    LoadFile lf = new LoadFile();
                    lf.AddressToLoad = onefile;
                    string[] manypath = onefile.Split('.');
                    lf.NameLoadFile = manypath[manypath.Length-2] + "." + manypath[manypath.Length-1];
                    setforwork.howDownload.LoadFile.Add(lf);

                    TempFiles.Add(onefile);
                }
                CopyFiles Temp = new CopyFiles(TempFiles, ".");
                this.SynchronizationObject = this;
                Temp.CopyAsync(this);
            }
            else
            {
                if (backgroundWorker1.IsBusy != true)
                {
                    LoadFile lf = new LoadFile();
                    lf.NameLoadFile = "nvdcve-2.0-modified";
                    lf.AddressToLoad = "http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-modified.xml";
                    setforwork.howDownload.LoadFile.Add(lf);

                    backgroundWorker1.RunWorkerAsync();
                }
            }
        }

        //Кнопка "Далее" таб №1
        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            LoadList();
            button2.Enabled = true;
            tabPage2.Parent = tabControl1;
            tabControl1.SelectedIndex = 1;
        }

        //выбор типа закачки - с сайта таб№1
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
            {
                setforwork.howDownload.LoadFromDisk = false;
            }
        }

        //выбор типа закачки с диска таб№1
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked == true)
            {
                setforwork.howDownload.LoadFromDisk = true;
                folderBrowserDialog1.ShowDialog();
            }
        }

        //кнопка "Стоп" таб№1
        private void button4_Click(object sender, EventArgs e)
        {
            button4.Enabled = false;
            if (setforwork.howDownload.LoadFromDisk)
            {
                RaiseCancel();
            }
            else
            {
                backgroundWorker1.CancelAsync();
                button1.Enabled = true;
            }

            if (backgroundWorker2.IsBusy)
            {
                backgroundWorker2.CancelAsync();
            }
        }


        //---------------------------------------Загрузка состояния из файла
        /// <summary>
        /// Загружает состояние Части HasDownload для настройки работы программы
        /// </summary>
        /// <param name="xnav"></param>
        private void LoadHasDownload(XPathNavigator xnav)
        {
            XPathNavigator nav = xnav.Clone();
            nav.MoveToFirstChild();
            if (nav.Value == "true")
            {
                setforwork.howDownload.LoadFromDisk = true;
            }
            else
            {
                setforwork.howDownload.LoadFromDisk = false;
            }
            nav.MoveToNext();
            bool hasSibling = true;
            while (hasSibling)
            {
                XPathNavigator navclone = nav.Clone();
                navclone.MoveToFirstChild();
                LoadFile lf = new LoadFile();
                lf.AddressToLoad = navclone.Value;
                navclone.MoveToNext();
                lf.NameLoadFile = navclone.Value;
                setforwork.howDownload.LoadFile.Add(lf);
                hasSibling = nav.MoveToNext();
            }
        }

        /// <summary>
        /// Загружает часть Service для настройки работы программы
        /// </summary>
        /// <param name="xnav"></param>
        private void LoadService(XPathNavigator xnav)
        {
            xnav.MoveToNext();
            xnav.MoveToFirstChild();
            bool hasSibling = true;
            while (hasSibling)
            {
                XPathNavigator navig = xnav.Clone();
                navig.MoveToFirstChild();
                ItServices its = new ItServices();
                its.ListPrograms = new List<String>();
                its.Name = navig.Value;
                navig.MoveToNext();
                its.Availability = navig.Value;
                navig.MoveToNext();
                its.Confidentialy = navig.Value;
                navig.MoveToNext();
                its.Integrity = navig.Value;

                navig.MoveToNext();
                if (navig.Value == "true")
                {
                    its.InternalMalefactor = true;
                }
                else
                {
                    its.InternalMalefactor = false;
                }
                navig.MoveToNext();
                if (navig.Value == "true")
                {
                    its.ExternalMalefactor = true;
                }
                else
                {
                    its.ExternalMalefactor = false;
                }

                navig.MoveToNext();
                navig.MoveToFirstChild();
                if (navig.HasChildren)
                {
                    bool HasSibling2 = true;
                    while (HasSibling2)
                    {
                        its.ListPrograms.Add(navig.Value);
                        HasSibling2 = navig.MoveToNext();
                    }
                }

                setforwork.Service.Add(its);
                hasSibling = xnav.MoveToNext();
            }
        }

        //Кнопка "Загрузить настройки" Таб №1
        private void button5_Click_1(object sender, EventArgs e)
        {
            button5.Enabled = false;
            openFileDialog1.ShowDialog();

            setforwork.howDownload.LoadFile.Clear();
            setforwork.Service.Clear();
            setforwork.howDownload.LoadFile = new List<LoadFile>();
            setforwork.Service = new List<ItServices>();

            String filepath = openFileDialog1.SafeFileName;
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(filepath);
            XPathNavigator xnav = xdoc.CreateNavigator();
            xnav.MoveToFirstChild();
            xnav.MoveToFirstChild();

            LoadHasDownload(xnav);

            LoadService(xnav);

            if (setforwork.howDownload.LoadFromDisk)
            {
                radioButton1.Checked = false;
                radioButton2.Checked = true;
            }
            else
            {
                radioButton1.Checked = true;
                radioButton2.Checked = false;
            }

            LoadList();
            button5.Enabled = true;
        }  



        //кнопка "Далее" таб №2
        private void button6_Click(object sender, EventArgs e)
        {
            tabPage3.Parent = tabControl1;
            tabControl1.SelectedIndex = 2;
        }

        //событие вызывается при изменении параметров DataGridView1 таб №2
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                //если строку добавили
                if (setforwork.Service == null || (e.RowIndex > setforwork.Service.Count - 1))
                {
                    AddNewRowServices(e);
                }
                else
                {
                    ChangeDataInDataGrid1(e);
                }
            }
        }

        /// <summary>
        /// Добавляет новый сервис со стандартными параметрами
        /// </summary>
        /// <param name="e"></param>
        public void AddNewRowServices(DataGridViewCellEventArgs e)
        {
            ItServices its = GetDefaultIts();
            its.Name = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            setforwork.Service.Add(its);
        }

        /// <summary>
        /// Изменяет содержимое структуры состояния, при изменении DataGrid1
        /// </summary>
        /// <param name="e"></param>
        public void ChangeDataInDataGrid1(DataGridViewCellEventArgs e)
        {
            //Собирает значения строки
            ItServices its = new ItServices();
            its.Name = setforwork.Service[e.RowIndex].Name;
            its.Confidentialy = setforwork.Service[e.RowIndex].Confidentialy;
            its.Availability = setforwork.Service[e.RowIndex].Availability;
            its.Integrity = setforwork.Service[e.RowIndex].Integrity;
            its.ExternalMalefactor = setforwork.Service[e.RowIndex].ExternalMalefactor;
            its.InternalMalefactor = setforwork.Service[e.RowIndex].InternalMalefactor;
            its.ListPrograms = setforwork.Service[e.RowIndex].ListPrograms;

            //Удаляет строку
            setforwork.Service.RemoveAt(e.RowIndex);

            //Смотрит какой параметр изменился, и изменяет его в структуре
            if (e.ColumnIndex == 0)
            {
                if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
                {
                    its.Name = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                }
                else
                {
                    its.Name = "";
                }
            }
            if (e.ColumnIndex == 1)
            {
                its.Confidentialy = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            }
            if (e.ColumnIndex == 2)
            {
                its.Integrity = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            }
            if (e.ColumnIndex == 3)
            {
                its.Availability = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            }

            //записывает данные в состояние
            setforwork.Service.Insert(e.RowIndex, its);
        }




        //кнопка "добавить продукт" таб №3
        private void button3_Click(object sender, EventArgs e)
        {
            foreach (ItServices its in setforwork.Service)
            {
                if (its.Name == comboBox1.Text)
                {
                    its.ListPrograms.Add(textBox2.Text);
                }
            }

            int i = 0;
            int newPO = 0;
            //определение строки куда вставляется ПО
            while (dataGridView2.Rows[i].Cells[0].Value.ToString().Contains(comboBox1.Text) == false)
            {
                i++;
            }
            newPO = i + 1;
            dataGridView2.Rows.Insert(newPO);

            dataGridView2.Rows[newPO].Cells[0].Value = " ";
            dataGridView2.Rows[newPO].Cells[1].Value = textBox2.Text;
        }
                
        //Кнопка "Далее" таб №3
        private void button7_Click(object sender, EventArgs e)
        {
            tabPage4.Parent = tabControl1;
            tabControl1.SelectedIndex = 3;
        }


        //Поле для записи названия ПО таб№3
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            listView1.Visible = false;
            listView1.Items.Clear();
            String NameProd = textBox2.Text;

            List<String> tmpLst = new List<String>();
            foreach (String prod in list)
            {
                if (prod.Contains(NameProd))
                {
                    tmpLst.Add(prod);
                    if (tmpLst.Count > 15)
                    {
                        break;
                    }
                }
            }
            
            if (tmpLst.Count != 0)
            {
                foreach (String prod in tmpLst)
                {
                    listView1.Items.Add(prod);
                }
            }
            else
            {
                if (NameProd.Length <= 3)
                {
                    listView1.Items.Add("Введите название ПО");
                }
                else
                {
                    listView1.Items.Add("Совпадений нет");
                }
            }
            listView1.Visible = true;
        }

        //Поле для выбора возможных вариантов ПО таб№3
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBox2.Text = listView1.FocusedItem.Text;
            listView1.Visible = false;
        }


        //Кнопка "Далее" таб №4
        private void button8_Click(object sender, EventArgs e)//Четвертая вкладка - Далее.
        {
            //Делаем таб №5 видимым
            tabPage5.Parent = tabControl1;
            tabControl1.SelectedIndex = 4;
        }

        //Вызывается при иземенении параметров злоумышленника DataGridView4 таб №4
        private void dataGridView4_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (e.ColumnIndex == 1)
                {
                    ItServices its = new ItServices();
                    its = setforwork.Service[e.RowIndex];
                    setforwork.Service.RemoveAt(e.RowIndex);
                    if (dataGridView4.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "Да")
                    {
                        its.InternalMalefactor = true;
                    }
                    else
                    {
                        its.InternalMalefactor = false;
                    }
                    setforwork.Service.Insert(e.RowIndex, its);
                }
                if (e.ColumnIndex == 2)
                {
                    ItServices its = new ItServices();
                    its = setforwork.Service[e.RowIndex];
                    setforwork.Service.RemoveAt(e.RowIndex);
                    if (dataGridView4.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "Да")
                    {
                        its.ExternalMalefactor = true;
                    }
                    else
                    {
                        its.ExternalMalefactor = false;
                    }
                    setforwork.Service.Insert(e.RowIndex, its);
                }
            }
        }



        public int POS = 0;
        public int Runner = 0;

        private void SearchInFile(String PathToFile)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(PathToFile);
            XPathNavigator xnav = doc.CreateNavigator();
            xnav.MoveToFirstChild();

            Int32 dataGridRows = dataGridView3.Rows.Count-1;
            String XpathProduct = "./*/*/*[name()='vuln:product']/text()";
            String XpathEntryToBaseScore = "./*/*/*[name()='cvss:score']/text()";
            XPathNodeIterator iter = xnav.Select(XpathProduct);

            //в каждом сервисе
            foreach (ItServices its in setforwork.Service)
            {
                //в для любой программы
                foreach (String prog in its.ListPrograms)
                {
                    XPathNodeIterator noditr = iter.Clone();
                    noditr.MoveNext();
                    bool hasSibling = true;
                    while (hasSibling)
                    {
                        XPathNavigator nav = noditr.Current;
                        if (nav.Value.ToString().Contains(prog))
                        {
                            nav.MoveToParent();
                            nav.MoveToParent();
                            nav.MoveToParent();
                            XPathNavigator navig = nav.Clone();
                            nav.MoveToFirstAttribute();
                            XPathNodeIterator iternavig = navig.Select(XpathEntryToBaseScore);
                            iternavig.MoveNext();
                            dataGridView3.Rows.Add();
                            dataGridView3.Rows[dataGridRows].Cells[0].Value = its.Name;
                            dataGridView3.Rows[dataGridRows].Cells[1].Value = prog;
                            dataGridView3.Rows[dataGridRows].Cells[2].Value = nav.Value.ToString();
                            dataGridView3.Rows[dataGridRows].Cells[3].Value = iternavig.Current.Value.ToString();
                            dataGridRows++;
                        }
                        hasSibling = noditr.MoveNext();
                    }
                }
            }
        }

        //Кнопка "Произвести анализ" таб №5
        public void button9_Click(object sender, EventArgs e)
        {
            dataGridView3.Rows.Clear();
            String[] ListBaseFiles = Directory.GetFiles(".", "nvdcve-2.0-20??.xml");
            for (Int32 count = 0; count < ListBaseFiles.Length; count++)
            {
                SearchInFile(ListBaseFiles[count]);
            }
            //SearchInFile(".\\nvdcve-2.0-2002.xml");
            //Runner = 0;
            //while ( Runner != dataGridView2.Rows.Count - 3 )
            //{
            //    if (dataGridView2.Rows[Runner].Cells[1].Value.ToString() != " ")//Исключаем пробелы, т.е. пустые строки.
            //    {
            //        QueryToBaseFiles(dataGridView2.Rows[Runner].Cells[1].Value.ToString(), dataGridView3);//Поисковик "базовых" характеристик.
            //    }
            //    Runner++;
            //}
        }

        //----------------------------------------Сохранение настроек программы
        /// <summary>
        /// Пишет в xdoc состояние метода загрузки
        /// </summary>
        /// <param name="xdoc">Документ куда пишем</param>
        /// <param name="howDownload">Элемент для записи способа и адресов загрузки</param>
        private void SaveSettingsToHowDownload(XmlDocument xdoc, XmlElement howDownload)
        {
            foreach (LoadFile lf in setforwork.howDownload.LoadFile)
            {
                XmlElement LoadFileElem = xdoc.CreateElement("LoadFile");

                XmlElement AddressToLoad = xdoc.CreateElement("AddressToLoad");
                XmlText TxtAddressToLoad = xdoc.CreateTextNode(lf.AddressToLoad);
                AddressToLoad.AppendChild(TxtAddressToLoad);
                XmlElement NameLoadFile = xdoc.CreateElement("NameFile");
                XmlText TxtNameLoadFile = xdoc.CreateTextNode(lf.NameLoadFile);
                NameLoadFile.AppendChild(TxtNameLoadFile);

                LoadFileElem.AppendChild(AddressToLoad);
                LoadFileElem.AppendChild(NameLoadFile);
                howDownload.AppendChild(LoadFileElem);
            }
        }

        /// <summary>
        /// Перебирает все сервисы по очереди, записывая их состояния в Service созданный в xdoc
        /// </summary>
        /// <param name="xdoc">Файл куда сохраняем</param>
        /// <param name="Service">Элемент для сервисов</param>
        private void SaveSettingsToItService(XmlDocument xdoc, XmlElement Service)
        {
            foreach (ItServices its in setforwork.Service)
            {
                XmlElement ItService = xdoc.CreateElement("ItService");
                Service.AppendChild(ItService);

                XmlElement Name = xdoc.CreateElement("Name");
                XmlText TxtName = xdoc.CreateTextNode(its.Name);
                Name.AppendChild(TxtName);
                ItService.AppendChild(Name);

                XmlElement Availability = xdoc.CreateElement("Availability");
                XmlText TxtAvailability = xdoc.CreateTextNode(its.Availability);
                Availability.AppendChild(TxtAvailability);
                ItService.AppendChild(Availability);

                XmlElement Confidentiality = xdoc.CreateElement("Confidentiality");
                XmlText TxtConfidentiality = xdoc.CreateTextNode(its.Confidentialy);
                Confidentiality.AppendChild(TxtConfidentiality);
                ItService.AppendChild(Confidentiality);

                XmlElement Integrity = xdoc.CreateElement("Integrity");
                XmlText TxtIntegrity = xdoc.CreateTextNode(its.Integrity);
                Integrity.AppendChild(TxtIntegrity);
                ItService.AppendChild(Integrity);

                XmlElement InternalMalefactor = xdoc.CreateElement("InternalMalefactor");
                XmlText TxtInternalMalefactor = xdoc.CreateTextNode(its.InternalMalefactor.ToString().ToLower());
                InternalMalefactor.AppendChild(TxtInternalMalefactor);
                ItService.AppendChild(InternalMalefactor);

                XmlElement ExternalMalefactor = xdoc.CreateElement("ExternalMalefactor");
                XmlText TxtExternalMalefactor = xdoc.CreateTextNode(its.ExternalMalefactor.ToString().ToLower());
                ExternalMalefactor.AppendChild(TxtExternalMalefactor);
                ItService.AppendChild(ExternalMalefactor);

                XmlElement ListPrograms = xdoc.CreateElement("ListPrograms");
                ItService.AppendChild(ListPrograms);
                if (its.ListPrograms != null && its.ListPrograms.Count != 0)
                {
                    foreach (String Prog in its.ListPrograms)
                    {
                        XmlElement Programs = xdoc.CreateElement("Program");
                        XmlText TxtPrograms = xdoc.CreateTextNode(Prog);
                        Programs.AppendChild(TxtPrograms);
                        ListPrograms.AppendChild(Programs);
                    }
                }
            }
        }

        /// <summary>
        /// Метод запускает сохранение текущего состояния программы в файл, имя файла берется из saveFileDialog1
        /// </summary>
        private void SaveSettings()
        {
            String filename = saveFileDialog1.FileName;
            XmlDocument xdoc = new XmlDocument();
            XmlElement xRoot = xdoc.DocumentElement;
            xRoot = xdoc.CreateElement("Root");
            xdoc.AppendChild(xRoot);

            XmlElement howDownload = xdoc.CreateElement("HowDownload");
            XmlElement Service = xdoc.CreateElement("Service");
            xRoot.AppendChild(howDownload);
            xRoot.AppendChild(Service);

            XmlElement LoadFromDisk = xdoc.CreateElement("LoadFromDisk");
            XmlText TxtLoadFromDisk = xdoc.CreateTextNode(setforwork.howDownload.LoadFromDisk.ToString().ToLower());
            LoadFromDisk.AppendChild(TxtLoadFromDisk);
            howDownload.AppendChild(LoadFromDisk);

            SaveSettingsToHowDownload(xdoc, howDownload);
            SaveSettingsToItService(xdoc, Service);

            xdoc.Save(filename);
        }

        //Кнопка "Сохранить настройки" таб №5
        private void button10_Click(object sender, EventArgs e)
        {
            saveFileDialog1.AddExtension = false;
            saveFileDialog1.ShowDialog();
            if (saveFileDialog1.ValidateNames)
            {
                SaveSettings();
            }
        }


        /// <summary>
        /// Загружает информацию о продуктах из файла по умолчанию productlist.xml
        /// </summary>
        private void LoadList()
        {
            XmlDocument docx = new XmlDocument();
            String filedictionary = "productlist.xml";
            docx.Load(filedictionary);
            XPathNavigator xnav = docx.CreateNavigator();

            xnav.MoveToFirstChild();
            //заполняет текстовое поле продуктов во вкладке программные компоненты, содержимым из словаря filedictionary
            LoadList(xnav);
        }

        /// <summary>
        /// Заполняет выпадающий список из файла ПО
        /// </summary>
        /// <param name="xnav">Навигатор на XmlDocument файл ПО</param>
        /// <param name="te"></param>
        private void LoadList(XPathNavigator xnav)
        {
            bool hasSibling = true;

            XPathNavigator nav = xnav.Clone();
            nav.MoveToFirstChild();
            while (hasSibling)
            {
                list.Add(nav.Value.ToString());
                hasSibling = nav.MoveToNext();
            }
        }
        
        public void QueryToBaseFiles(String ProductName, DataGridView table)//Обращение к "базовым" файлам. Тут тупой копипаст. Ну... Почти))
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                //String filename = "nvdcve-2.0-2002.xml";
                //doc.Load(filename);
                //XPathNavigator xnav = doc.CreateNavigator();
                //xnav.MoveToFirstChild();
                //xnav.MoveToFirstChild();
                //OutScore(xnav, ProductName, table);

                String filename = "nvdcve-2.0-2003.xml";
                doc.Load(filename);
                XPathNavigator xnav = doc.CreateNavigator();
                xnav.MoveToFirstChild();
                xnav.MoveToFirstChild();
                OutScore(xnav, ProductName, table);

                filename = "nvdcve-2.0-2004.xml";
                doc.Load(filename);
                xnav = doc.CreateNavigator();
                xnav.MoveToFirstChild();
                xnav.MoveToFirstChild();
                OutScore(xnav, ProductName, table);

                filename = "nvdcve-2.0-2005.xml";
                doc.Load(filename);
                xnav = doc.CreateNavigator();
                xnav.MoveToFirstChild();
                xnav.MoveToFirstChild();
                OutScore(xnav, ProductName, table);

                filename = "nvdcve-2.0-2006.xml";
                doc.Load(filename);
                xnav = doc.CreateNavigator();
                xnav.MoveToFirstChild();
                xnav.MoveToFirstChild();
                OutScore(xnav, ProductName, table);

                filename = "nvdcve-2.0-2007.xml";
                doc.Load(filename);
                xnav = doc.CreateNavigator();
                xnav.MoveToFirstChild();
                xnav.MoveToFirstChild();
                OutScore(xnav, ProductName, table);

                filename = "nvdcve-2.0-2008.xml";
                doc.Load(filename);
                xnav = doc.CreateNavigator();
                xnav.MoveToFirstChild();
                xnav.MoveToFirstChild();
                OutScore(xnav, ProductName, table);

                filename = "nvdcve-2.0-2009.xml";
                doc.Load(filename);
                xnav = doc.CreateNavigator();
                xnav.MoveToFirstChild();
                xnav.MoveToFirstChild();
                OutScore(xnav, ProductName, table);

                filename = "nvdcve-2.0-2010.xml";
                doc.Load(filename);
                xnav = doc.CreateNavigator();
                xnav.MoveToFirstChild();
                xnav.MoveToFirstChild();
                OutScore(xnav, ProductName, table);

                filename = "nvdcve-2.0-2011.xml";
                doc.Load(filename);
                xnav = doc.CreateNavigator();
                xnav.MoveToFirstChild();
                xnav.MoveToFirstChild();
                OutScore(xnav, ProductName, table);
            }
            catch (Exception e)
            {
                //написать что не все файлы загружены
                //но, скорее всего он будет искать только по имеющимся файлам
            }
        }

        /// <summary>
        /// Вывод информации из базы данных. Сейчас это только id и basescore
        /// </summary>
        /// <param name="xnav"></param>
        /// <param name="ProductName"></param>
        /// <param name="table"></param>
        public void OutScore(XPathNavigator xnav, String ProductName, DataGridView table)
        {
            bool hasSibling = true;

            String temp;
            while (hasSibling)
            {
                temp = "";
                int pos;
                pos = Runner;

                //Находит категорию к которой принадлежит продукт
                while (dataGridView2.Rows[pos].Cells[0].Value.ToString() == " ")
                { pos--; }

                bool ind = false;
                String text = "";
                String text1 = "";
                String confy = "";
                String integ = "";
                String avail = "";
                
                XPathNodeIterator iter;
                XPathNavigator nav = xnav.Clone();
                String xpath = "";
                //ID
                xpath = "./*[name()='vuln:cve-id']/text()";
                iter = nav.Select(xpath);
                iter.MoveNext();
                XPathNavigator navig3 = iter.Current;
                navig3.MoveToFirstAttribute();
                navig3.MoveToNextAttribute();
                navig3.MoveToNextAttribute();
                text = navig3.Value.ToString();

                //product  1
                xpath = "./*/*[name()='vuln:product']/text()";
                iter = nav.Select(xpath);
                iter.MoveNext();
                XPathNavigator navig2 = iter.Current;
                navig2.MoveToFirstAttribute();
                navig2.MoveToNextAttribute();
                navig2.MoveToNextAttribute();
                while (temp != navig2.Value.ToString())
                {
                    if (navig2.Value.Substring(7) == ProductName)
                    {
                        ind = true;
                    }
                    navig2.MoveToNext();
                    temp = navig2.Value.ToString();
                    iter.MoveNext();
                }
                
                int counter = 0;
                bool ind1 = false;
                bool ind2 = false;
                bool ind3 = false;
                //FILTERS
                //confy
                xpath = "./*/*/*[name()='cvss:confidentiality-impact']/text()";
                iter = nav.Select(xpath);
                iter.MoveNext();
                XPathNavigator navig4 = iter.Current;
                navig4.MoveToFirstAttribute();
                navig4.MoveToNextAttribute();
                navig4.MoveToNextAttribute();
                confy = navig4.Value.ToString();
                //dataGridView2.Rows[pos].Cells[0].Value - это имя сервиса.
                while (dataGridView1.Rows[counter].Cells[0].Value != dataGridView2.Rows[pos].Cells[0].Value)
                {
                    counter++;
                } 
                if (dataGridView1.Rows[counter].Cells[1].Value.ToString() == "Low")
                    {
                        if (confy == "COMPLETE")
                        { ind1 = true; }
                    }
                if (dataGridView1.Rows[counter].Cells[1].Value.ToString() == "Medium")
                    {
                        if ((confy == "PARTIAL") || (confy == "COMPLETE"))
                        { ind1 = true; }
                    }
                if (dataGridView1.Rows[counter].Cells[1].Value.ToString() == "High")
                    {
                        if ((confy == "COMPLETE") || (confy == "PARTIAL") || (confy == "NONE"))
                        { ind1 = true; }
                    }
                
                //integrity
                xpath = "./*/*/*[name()='cvss:integrity-impact']/text()";
                iter = nav.Select(xpath);
                iter.MoveNext();
                XPathNavigator navig5 = iter.Current;
                navig5.MoveToFirstAttribute();
                navig5.MoveToNextAttribute();
                navig5.MoveToNextAttribute();
                integ = navig5.Value.ToString();
                if (dataGridView1.Rows[counter].Cells[2].Value.ToString() == "Low")
                    {
                        if (integ == "COMPLETE")
                        { ind2 = true; }
                    }
                if (dataGridView1.Rows[counter].Cells[2].Value.ToString() == "Medium")
                    {
                        if ((integ == "PARTIAL") || (integ == "COMPLETE"))
                        { ind2 = true; }
                    }
                if (dataGridView1.Rows[counter].Cells[2].Value.ToString() == "High")
                    {
                        if ((integ == "COMPLETE") || (integ == "PARTIAL") || (integ == "NONE"))
                        { ind2 = true; }
                    }
                
                //availability
                xpath = "./*/*/*[name()='cvss:integrity-impact']/text()";
                iter = nav.Select(xpath);
                iter.MoveNext();
                XPathNavigator navig6 = iter.Current;
                navig6.MoveToFirstAttribute();
                navig6.MoveToNextAttribute();
                navig6.MoveToNextAttribute();
                avail = navig6.Value.ToString();
                if (dataGridView1.Rows[counter].Cells[3].Value.ToString() == "Low")
                    {
                        if (avail == "COMPLETE")
                        { ind3 = true; }
                    }
                if (dataGridView1.Rows[counter].Cells[3].Value.ToString() == "Medium")
                    {
                        if ((avail == "PARTIAL") || (avail == "COMPLETE"))
                        { ind3 = true; }
                    }
                if (dataGridView1.Rows[counter].Cells[3].Value.ToString() == "High")
                    {
                        if ((avail == "COMPLETE") || (avail == "PARTIAL") || (avail == "NONE"))
                        { ind3 = true; }
                    }
                //END OF FILTERS
                if ((ind1 == false) && (ind2 == false) && (ind3 == false))
                { ind = false; }

                //cvss:score  4
                xpath = "./*/*/*[name()='cvss:score']/text()";
                iter = nav.Select(xpath);
                iter.MoveNext();
                XPathNavigator navig1 = iter.Current;
                navig1.MoveToFirstAttribute();
                navig1.MoveToNextAttribute();
                navig1.MoveToNextAttribute();
                text1 = text1 + navig1.Value;
                if (ind == true)
                {
                    table.Rows.Add(1);
                    table.Rows[POS].Cells[0].Value = dataGridView2.Rows[pos].Cells[0].Value;
                    table.Rows[POS].Cells[1].Value = ProductName;
                    table.Rows[POS].Cells[2].Value = text;
                    table.Rows[POS].Cells[3].Value = text1;
                    POS++;
                }
                //vuln:summary  14
                xpath = "./*[name()='vuln:summary']/text()";
                iter = nav.Select(xpath);
                iter.MoveNext();

                text = "";
                text1 = "";
                ind = false;
                hasSibling = xnav.MoveToNext();
             }    
        }



        //---------------------------------------------------Скачивание файлов совместно с получением списка ПО
        /// <summary>
        /// Выполняет скачку файлов в отдельном потоке, и отсылает уведомления в окно
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Cernel cr = new Cernel();


            cr.AddLoadingIfNo(new Loading(setforwork.howDownload.LoadFile[0].AddressToLoad , setforwork.howDownload.LoadFile[0].NameLoadFile));
            //cr.AddLoadingIfNo(new Loading(setforwork.howDownload.LoadFile[0].AddressToLoad, setforwork.howDownload.LoadFile[0].AddressToLoad));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-modified.xml", "nvdcve-2.0-modified"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2002.xml", "nvdcve-2.0-2002"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2003.xml", "nvdcve-2.0-2003"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2004.xml", "nvdcve-2.0-2004"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2005.xml", "nvdcve-2.0-2005"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2006.xml", "nvdcve-2.0-2006"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2007.xml", "nvdcve-2.0-2007"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2008.xml", "nvdcve-2.0-2008"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2009.xml", "nvdcve-2.0-2009"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2010.xml", "nvdcve-2.0-2010"));
            //cr.AddLoadingIfNo(new Loading("http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2011.xml", "nvdcve-2.0-2011"));

            int numbPart = cr.GetNumbersPart();

            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 0; i < numbPart; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    bool PartIsDownloaded;
                    PartIsDownloaded = cr.StartElem();
                    if (!PartIsDownloaded)
                    {
                        i--;
                    }
                    worker.ReportProgress(((i + 1) * 100) / numbPart);
                }
            }
        }

        /// <summary>
        /// изменение progressbar1 по событию скачки одной части
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        /// <summary>
        /// выполняется по окончании или остановке процесса загрузки
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                button4.Enabled = false;
                button1.Enabled = true;
                button2.Enabled = true;
                radioButton1.Enabled = true;
                radioButton2.Enabled = true;
                progressBar1.Value = 100;
            }
            else
            {
                StartGetPOList();
            }
        }



        //---------------------------------------------------Копирование файлов
        /// <summary>
        /// Метод для потока CopyFiles, отображает прогресс процесса копирования
        /// </summary>
        /// <param name="totalFiles"></param>
        /// <param name="copiedFiles"></param>
        /// <param name="totalBytes"></param>
        /// <param name="copiedBytes"></param>
        /// <param name="currentFilename"></param>
        /// <param name="AlltotalSize"></param>
        /// <param name="AllCopyedBytes"></param>
        public void update(Int32 totalFiles, Int32 copiedFiles, Int64 totalBytes, Int64 copiedBytes, String currentFilename, Int64 AlltotalSize, Int64 AllCopyedBytes)
        {
            if (AlltotalSize != 0)
            {
                progressBar1.Value = Convert.ToInt32(100f * ((AllCopyedBytes + copiedBytes) / 1024f) / (AlltotalSize / 1024f));
            }

            label1.Text = "(" + (copiedFiles + 1) + "/" + totalFiles + ")" + currentFilename;
        }

        /// <summary>
        /// выполняется по окончанию процесса копирования, либо при отмене
        /// </summary>
        public void enablefinish()
        {
            StartGetPOList();
        }

        //Событие отмены копирования
        public event CopyFiles.DEL_cancelCopy EN_cancelCopy;

        /// <summary>
        /// Функция вызова события отмены копирования
        /// </summary>
        private void RaiseCancel()
        {
            if (EN_cancelCopy != null)
            {
                EN_cancelCopy();
            }
        }



        //---------------------------------------------------Получение списка ПО
        private void StartGetPOList()
        {
            if (backgroundWorker2.IsBusy != true)
            {
                label1.Text = "Идет загрузка..";
                backgroundWorker2.RunWorkerAsync();
            }
        }

        /// <summary>
        /// Добавляет к liststring все продукты в текущем файле, xnav
        /// </summary>
        /// <param name="xnav"></param>
        /// <param name="liststring"></param>
        private static void getAllProduct(XPathNavigator xnav, List<String> liststring)
        {
            String xPath = "./*/*[name()='vuln:vulnerable-software-list']/*[name()='vuln:product']/text()";
            XPathNodeIterator iter;

            xnav.MoveToFirstChild();
            iter = xnav.Select(xPath);

            foreach (XPathNavigator navig in iter)
            {
                liststring.Add(navig.Value);
            }
        }

        /// <summary>
        /// Запускается для составления списка продуктов по имеющимся файлам
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            //переменные для управления созданием списка ПО
            String lister = "productlist.xml";
            FileStream fs = new FileStream(lister, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 7, FileOptions.RandomAccess);
            StreamWriter sw = new StreamWriter(fs);
            List<String> liststring = new List<String>();
            BackgroundWorker worker = sender as BackgroundWorker;

            sw.Write("<product-list>\n");
            XmlDocument doc = new XmlDocument();
            foreach (String FilePath in System.IO.Directory.GetFiles(".", "nvdcve-2.0-20??.xml"))
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    doc.Load(FilePath);
                    XPathNavigator xnav = doc.CreateNavigator();
                    getAllProduct(xnav, liststring);
                }
            }

            if (liststring != null)
            {
                //in .net 3.5 faster then .net 2.0 works time 12 sec
                //
                //IEnumerable<String> distinctString = liststring.Distinct();
                //foreach (String starrrring in distinctString)
                //{
                //    sw.Write(starrrring.Remove(0, 5) + "\n");
                //}

                //in .net2.0 works time 3 min
                liststring.Sort();
                Int32 index = 0;
                Int32 indexiter = 0;
                Int32 CountObjAll = liststring.Count;
                while (index < liststring.Count - 1)
                {
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        if (liststring[index] == liststring[index + 1])
                        {
                            liststring.RemoveAt(index);
                        }
                        else
                        {
                            sw.WriteLine("<product>" + liststring[index].Remove(0, 7) + "</product>");
                            index++;
                        }
                        indexiter++;
                        worker.ReportProgress(indexiter * 100 / CountObjAll);
                    }
                }
            }

            sw.Write("</product-list>\n");
            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// Выполняется для отображения прогресса процесса поиска ПО
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            label1.Text ="Составление списка продуктов: " + e.ProgressPercentage.ToString()+" %";
        }

        /// <summary>
        /// выполняется по окончании или остановке процесса получения списка ПО
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {           
            button1.Enabled = true;
            button2.Enabled = true;
            button4.Enabled = false;
            radioButton1.Enabled = true;
            radioButton2.Enabled = true;
            label1.Text = "";
            progressBar1.Value = 0;
        }




        //-------------------------------------------------Вывод состояний табов 2,3,4
        /// <summary>
        /// Вызывается при изменении вкладки программы.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            if (e.TabPageIndex == 1)
            {
                CheckTab2();
            }
            if (e.TabPageIndex == 2)
            {
                CheckTab3();
            }
            if (e.TabPageIndex == 3)
            {
                CheckTab4();
            }
            
        }

        /// <summary>
        /// Метод обновляет содержимое таб №2, согласно параметрам состояния
        /// </summary>
        private void CheckTab2()
        {
            Int32 count = setforwork.Service.Count;
            dataGridView1.Rows.Clear();
            for (Int32 NumbStr = 0; NumbStr < count; NumbStr++)
            {
                ItServices its = setforwork.Service[NumbStr];
                dataGridView1.Rows.Add();
                dataGridView1.Rows[NumbStr].Cells[0].Value = its.Name;
                dataGridView1.Rows[NumbStr].Cells[1].Value = its.Confidentialy;
                dataGridView1.Rows[NumbStr].Cells[2].Value = its.Integrity;
                dataGridView1.Rows[NumbStr].Cells[3].Value = its.Availability;
            }
        }

        /// <summary>
        /// Метод обновляет содержимое таб №3, согласно параметрам состояния
        /// </summary>
        private void CheckTab3()
        {
            Int32 count = setforwork.Service.Count;
            Int32 AllCount = -1;
            dataGridView2.Rows.Clear();
            comboBox1.Items.Clear();
            for (Int32 NumbStr = 0; NumbStr < count; NumbStr++)
            {
                ItServices its = setforwork.Service[NumbStr];
                dataGridView2.Rows.Add();
                AllCount++;
                dataGridView2.Rows[AllCount].Cells[0].Value = its.Name;
                dataGridView2.Rows[AllCount].Cells[1].Value = "";
                comboBox1.Items.Add(its.Name);
                if (its.ListPrograms != null && its.ListPrograms.Count != 0)
                {
                    Int32 ListCount = its.ListPrograms.Count;
                    for (Int32 prog = 0; prog < ListCount; prog++)
                    {
                        dataGridView2.Rows.Add();
                        AllCount++;
                        dataGridView2.Rows[AllCount].Cells[1].Value = its.ListPrograms[prog];
                        dataGridView2.Rows[AllCount].Cells[0].Value = "";
                    }
                }

            }
        }

        /// <summary>
        /// Метод обновляет содержимое таб №4, согласно параметрам состояния
        /// </summary>
        private void CheckTab4()
        {
            Int32 count = setforwork.Service.Count;
            dataGridView4.Rows.Clear();
            for (Int32 NumbStr = 0; NumbStr < count; NumbStr++)
            {
                ItServices its = setforwork.Service[NumbStr];
                dataGridView4.Rows.Add();
                dataGridView4.Rows[NumbStr].Cells[0].Value = its.Name;
                if (its.InternalMalefactor)
                {
                    dataGridView4.Rows[NumbStr].Cells[1].Value = "Да";
                }
                else
                {
                    dataGridView4.Rows[NumbStr].Cells[1].Value = "Нет";
                }
                if (its.ExternalMalefactor)
                {
                    dataGridView4.Rows[NumbStr].Cells[2].Value = "Да";
                }
                else
                {
                    dataGridView4.Rows[NumbStr].Cells[2].Value = "Нет";
                }
            }
        }


        /// <summary>
        /// Возвращяет ItServices со стандартными параметрами
        /// </summary>
        /// <returns></returns>
        public ItServices GetDefaultIts()
        {
            ItServices its = new ItServices();
            its.Name = "";
            its.ListPrograms = new List<String>();
            its.Confidentialy = "Low";
            its.Availability = "Low";
            its.Integrity = "Low";
            its.InternalMalefactor = true;
            its.ExternalMalefactor = true;
            return its;
        }


        
    }


    //Структуры
    
    //---------Структуры настройки ПО

    /// <summary>
    /// Содержит информацию о загрузке имя и адрес файла
    /// </summary>
    public struct LoadFile
    {
        public String AddressToLoad;
        public String NameLoadFile;
    }

    /// <summary>
    /// Хранит информацию о способе загрузки и список загрузок
    /// </summary>
    public struct HowDownload
    {
        public bool LoadFromDisk;
        public List<LoadFile> LoadFile;
    }

    /// <summary>
    /// Хранит информацию об одном конкретном сервисе
    /// </summary>
    public struct ItServices
    {
        public String Name;
        public String Confidentialy;
        public String Integrity;
        public String Availability;
        public List<String> ListPrograms;
        public bool InternalMalefactor;
        public bool ExternalMalefactor;
    }

    /// <summary>
    /// Хранит информацио о настройках программы
    /// </summary>
    public struct SettingsForWork
    {
        public HowDownload howDownload;
        public List<ItServices> Service;
    }


    //--------Структуры результатов Исследования
    /// <summary>
    /// Хранит все сервисы и их состояние
    /// </summary>
    public struct ResCalc
    {
        List<ResItServices> ResIS;
    }

    /// <summary>
    /// Хранит информацию Отдельного сервиса - все ПО и их состояния
    /// </summary>
    public struct ResItServices
    {
        List<ResPo> ResPo;
    }

    /// <summary>
    /// Хранит информацию об отдельном ПО
    /// </summary>
    public struct ResPo
    {
        List<ResCVSS> ResCVSS;
    }

    /// <summary>
    /// Хранит информацию об ошибках в ПО
    /// </summary>
    public struct ResCVSS
    {
        String Id;
        float BaseScore;
    }
}

